package com.ruoyi.quartz.task;
import com.ruoyi.eduManage.domain.dto.DailyStatisticsMailDTO;
import com.ruoyi.eduManage.service.IMailDataService;
import com.ruoyi.eduManage.utils.MailUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时邮件任务
 * 
 * @author ruoyi
 */
@Component("mailTask")
public class MailTask {
    
    private static final Logger logger = LoggerFactory.getLogger(MailTask.class);
    
    @Autowired
    private MailUtils mailUtils;
    
    @Autowired
    private IMailDataService mailDataService;
    
    /**
     * 发送每日统计邮件给所有教师
     * 获取前一天的数据并发送邮件
     */
    public void sendDailyStatisticsMail() {
        try {
            // 获取前一天的日期
            LocalDate yesterday = LocalDate.now().minusDays(1);
            String dateStr = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            
            logger.info("开始发送每日统计邮件，统计日期: {}", dateStr);
            
            // 调用mailDataService获取所有教师的统计数据
            List<DailyStatisticsMailDTO> statisticsList = mailDataService.getAllTeachersDailyStatistics(
                dateStr, dateStr, 1);
            
            if (statisticsList == null || statisticsList.isEmpty()) {
                logger.warn("未找到任何教师统计数据，日期: {}", dateStr);
                return;
            }
            
            int successCount = 0;
            int failCount = 0;
            
            // 为每个教师发送邮件
            for (DailyStatisticsMailDTO statistics : statisticsList) {
                try {
                    // 准备模板变量
                    Map<String, Object> variables = new HashMap<>();
                    variables.put("teacherName", statistics.getTeacherName());
                    variables.put("startDate", statistics.getStartDate());
                    variables.put("endDate", statistics.getEndDate());
                    variables.put("classDataList", statistics.getClassDataList());
                    
                    // 发送邮件
                    String subject = String.format("学生打卡统计报告 - %s", dateStr);
                    boolean success = mailUtils.sendTemplateMailWithConfig(
                        statistics.getTeacherEmail(),
                        subject,
                        "daily-statistics-simple",
                        variables,
                        true  // 使用激活的配置
                    );
                    
                    if (success) {
                        successCount++;
                        logger.info("邮件发送成功，教师: {}, 邮箱: {}", 
                            statistics.getTeacherName(), statistics.getTeacherEmail());
                    } else {
                        failCount++;
                        logger.error("邮件发送失败，教师: {}, 邮箱: {}", 
                            statistics.getTeacherName(), statistics.getTeacherEmail());
                    }
                } catch (Exception e) {
                    failCount++;
                    logger.error("发送邮件异常，教师: {}, 错误: {}", 
                        statistics.getTeacherName(), e.getMessage());
                }
            }
            
            logger.info("每日统计邮件发送完成，成功: {}, 失败: {}", successCount, failCount);
            
        } catch (Exception e) {
            logger.error("发送每日统计邮件任务执行失败: {}", e.getMessage(), e);
        }
    }
}